package com.beemans.common.utils

import android.animation.Animator
import android.animation.ValueAnimator
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.viewpager2.widget.ViewPager2

/**
 * @author tiamosu
 * @date 2021/9/16.
 *
 * 修改[ViewPager2]切换速度
 */
class ViewPager2Helper(private val viewPager2: ViewPager2) {

    /**
     * 保存前一个animatedValue
     */
    private var previousValue = 0

    /**
     * 设置当前Item
     *
     * @param item          下一个跳转的item
     * @param duration      scroll时长
     */
    fun setCurrentItem(item: Int, duration: Long = 0) {
        val currentItem = viewPager2.currentItem
        if (item == currentItem) {
            return
        }
        viewPager2.post {
            val pagePxWidth = viewPager2.width
            val pxToDrag = pagePxWidth * (item - currentItem)
            previousValue = 0

            ValueAnimator.ofInt(0, pxToDrag).apply {
                this.interpolator = AccelerateDecelerateInterpolator()
                //某些低端手机duration为0时，会导致setCurrentItem无效
                this.duration = if (duration <= 0L) 1 else duration
                addUpdateListener {
                    val currentValue = it.animatedValue as? Int ?: 0
                    val currentPxToDrag = (currentValue - previousValue).toFloat()
                    viewPager2.fakeDragBy(-currentPxToDrag)
                    previousValue = currentValue
                }
                addListener(object : Animator.AnimatorListener {
                    override fun onAnimationStart(animation: Animator) {
                        viewPager2.beginFakeDrag()
                    }

                    override fun onAnimationEnd(animation: Animator) {
                        viewPager2.endFakeDrag()
                    }

                    override fun onAnimationCancel(animation: Animator) {}
                    override fun onAnimationRepeat(animation: Animator) {}
                })
                start()
            }
        }
    }
}